package com.fbli.shirodemo.config;

import com.fbli.shirodemo.pojo.User;
import com.fbli.shirodemo.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {
    @Autowired
    UserService userService;
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了doGetAuthorizationInfo");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //info.addStringPermission("user:add");
        //拿到当前登录的这个对象
        Subject subject= SecurityUtils.getSubject();
        User currentUser = (User)subject.getPrincipal();
        //设置登录的请求
        info.addStringPermission(currentUser.getPerms());
        return info;
    }
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了doGetAuthenticationInfo");
        //用户名，密码 数据库取

        UsernamePasswordToken userToken=(UsernamePasswordToken) token;
        User user = userService.queryUserName(userToken.getUsername());
        if(user==null){
            return null;//抛出异常 UnknownAccountException
        }
        Subject currentSubject = SecurityUtils.getSubject();
        Session session = currentSubject.getSession();
        session.setAttribute("loginUser",user);
        //密码认证，shiro做~
        return new SimpleAuthenticationInfo(user,user.getPassword(),getName());
    }
}
